package dos

import (
	"bytes"
	"fmt"
	"os"
	"sync"
	"time"
)

// DOSExporter DOS攻击报告导出工具
type DOSExporter struct {
	evaluation *DOSAttackEvaluation
}

// NewDOSExporter 创建新的DOS攻击报告导出工具
func NewDOSExporter(evaluation *DOSAttackEvaluation) *DOSExporter {
	return &DOSExporter{
		evaluation: evaluation,
	}
}

// ExportReport 导出攻击报告
func (e *DOSExporter) ExportReport(outputDir string) (string, error) {
	// 确保输出目录存在
	if err := os.MkdirAll(outputDir, 0755); err != nil {
		return "", fmt.Errorf("创建输出目录失败: %v", err)
	}

	// 生成报告文件名，使用当前时间戳
	reportFileName := fmt.Sprintf("%s/dos_attack_report_%d.txt", outputDir, time.Now().Unix())

	// 创建报告文件
	file, err := os.Create(reportFileName)
	if err != nil {
		return "", fmt.Errorf("创建报告文件失败: %v", err)
	}
	defer file.Close()

	// 获取报告内容
	reportContent := e.generateReportContent()

	// 写入报告内容
	_, err = file.WriteString(reportContent)
	if err != nil {
		return "", fmt.Errorf("写入报告文件失败: %v", err)
	}

	return reportFileName, nil
}

// generateReportContent 生成报告内容
func (e *DOSExporter) generateReportContent() string {
	e.evaluation.mutex.RLock()
	defer e.evaluation.mutex.RUnlock()

	var buffer bytes.Buffer

	buffer.WriteString("============================================\n")
	buffer.WriteString("          DOS攻击效果评估报告              \n")
	buffer.WriteString("============================================\n\n")

	// 添加攻击时间信息
	buffer.WriteString(fmt.Sprintf("攻击开始时间: %s\n", e.evaluation.startTime.Format("2006-01-02 15:04:05")))
	buffer.WriteString(fmt.Sprintf("攻击结束时间: %s\n", e.evaluation.endTime.Format("2006-01-02 15:04:05")))
	buffer.WriteString(fmt.Sprintf("攻击持续时间: %.2f秒\n\n", e.evaluation.endTime.Sub(e.evaluation.startTime).Seconds()))

	// 添加性能影响信息
	buffer.WriteString("【性能影响】\n")
	buffer.WriteString(fmt.Sprintf("攻击前平均响应时间: %.3f秒\n", e.evaluation.preAttackResponseTime))
	buffer.WriteString(fmt.Sprintf("攻击后平均响应时间: %.3f秒\n", e.evaluation.postAttackResponseTime))

	responseTimeChange := ((e.evaluation.postAttackResponseTime - e.evaluation.preAttackResponseTime) /
		e.evaluation.preAttackResponseTime) * 100

	if responseTimeChange > 0 {
		buffer.WriteString(fmt.Sprintf("响应时间增加: %.1f%%\n\n", responseTimeChange))
	} else {
		buffer.WriteString(fmt.Sprintf("响应时间减少: %.1f%%\n\n", -responseTimeChange))
	}

	// 添加可用性影响信息
	buffer.WriteString("【可用性影响】\n")
	buffer.WriteString(fmt.Sprintf("攻击前请求成功率: %.1f%%\n", e.evaluation.preAttackSuccessRate))
	buffer.WriteString(fmt.Sprintf("攻击后请求成功率: %.1f%%\n", e.evaluation.postAttackSuccessRate))

	successRateChange := e.evaluation.postAttackSuccessRate - e.evaluation.preAttackSuccessRate

	if successRateChange < 0 {
		buffer.WriteString(fmt.Sprintf("请求成功率下降: %.1f%%\n\n", -successRateChange))
	} else {
		buffer.WriteString(fmt.Sprintf("请求成功率上升: %.1f%%\n\n", successRateChange))
	}

	// 添加综合评估信息
	overallImpact := (e.evaluation.performanceImpact + e.evaluation.availabilityImpact) / 2

	var effectivenessLevel string
	switch {
	case overallImpact >= 0.8:
		effectivenessLevel = "极高"
	case overallImpact >= 0.6:
		effectivenessLevel = "高"
	case overallImpact >= 0.3:
		effectivenessLevel = "中"
	case overallImpact >= 0.1:
		effectivenessLevel = "低"
	default:
		effectivenessLevel = "极低"
	}

	buffer.WriteString("【综合评估】\n")
	buffer.WriteString(fmt.Sprintf("性能影响评分: %.2f/1.00\n", e.evaluation.performanceImpact))
	buffer.WriteString(fmt.Sprintf("可用性影响评分: %.2f/1.00\n", e.evaluation.availabilityImpact))
	buffer.WriteString(fmt.Sprintf("综合影响评分: %.2f/1.00\n", overallImpact))
	buffer.WriteString(fmt.Sprintf("攻击效果级别: %s\n\n", effectivenessLevel))

	// 添加状态码统计
	buffer.WriteString("【状态码统计】\n")
	for code, count := range e.evaluation.statusCodeHistory {
		buffer.WriteString(fmt.Sprintf("HTTP %d: %d 个\n", code, count))
	}

	buffer.WriteString("\n============================================\n")

	return buffer.String()
}

// DOSAttackEvaluation DOS攻击评估数据结构
type DOSAttackEvaluation struct {
	preAttackResponseTime  float64       // 攻击前的平均响应时间
	postAttackResponseTime float64       // 攻击后的平均响应时间
	preAttackSuccessRate   float64       // 攻击前的请求成功率
	postAttackSuccessRate  float64       // 攻击后的请求成功率
	availabilityImpact     float64       // 可用性影响评分 (0-1)
	performanceImpact      float64       // 性能影响评分 (0-1)
	startTime              time.Time     // 攻击开始时间
	endTime                time.Time     // 攻击结束时间
	evaluationSamples      int           // 评估样本数
	responseTimeHistory    []float64     // 响应时间历史记录
	statusCodeHistory      map[int]int   // 状态码历史统计
	mutex                  *sync.RWMutex // 用于并发访问保护
}
